/**
 * Created by chencheng on 17-8-31.
 */

import { Component } from 'react';

import { MainHeader, MainContent } from 'templates/MainLayout/MainLayout';
import { EnumModalType } from 'constants/EnumType';
import {
    Table, Button, Input, Icon, Modal, Form
} from 'antd';
const FormItem = Form.Item;

import T from 'utils/T';
import {
    getUserListAction,
    startUserAction,
    stopUserAction,
    delUserAction,
    addUserAction,
    updateUserAction
} from '../../actions/userManager/index';

export default class UserManager extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: []
        };
    }

    componentDidMount() {
        this.loadData();
    }

    loadData() {
        getUserListAction().then(resp => {
            this.setState({
                dataSource: resp.data.map((item, index) => {
                    return {
                        ...item,
                        key: index,
                        id: index + 1
                    };
                })
            });
        }, resp => {
            T.prompt.error(resp.msg);
        });
    }

    handleEditUser = (info) => {
        T.helper.renderModal(<AddEditUserForm type={EnumModalType.edit.type} info={info} />);
    };

    handleAddUser = () => {
        T.helper.renderModal(<AddEditUserForm type={EnumModalType.add.type} />);
    };


    handleStop = (record) => {
        stopUserAction(record.user_id).then(resp => {
            T.prompt.success('已禁用');
            this.loadData();
        }, resp => {
            T.prompt.error(resp.msg);
        });
    }

    handleUp = (record) => {
        startUserAction(record.user_id).then(resp => {
            T.prompt.success('已启用');
            this.loadData();
        }, resp => {
            T.prompt.error(resp.msg);
        });
    };

    handleDel = (record) => {
        T.prompt.confirm(() => {
            delUserAction(record.user_id).then(resp => {
                T.prompt.success('已删除');
            }, resp => {
                T.prompt.error(resp.msg);
            });
        }, {
            title: '确定删除该用户信息吗？',
            content: '一旦删除，该账户不可再用',
            okText: '确定',
            cancelText: '取消'
        });
    }

    render() {
        const columns = [
            {
                title: '序号',
                dataIndex: 'id'
            },
            {
                title: '姓名',
                dataIndex: 'user_name'
            },
            {
                title: '邮箱',
                dataIndex: 'user_email'
            },
            {
                title: '状态',
                dataIndex: 'user_status',
                render: text => {
                    return Number(text) === 1 ? '正常' : '禁用';
                },
            },
            {
                title: '操作',
                dataIndex: 'operation',
                render: (text, record) => {
                    return Number(record.user_status) === 1 ? <div>
                        <Button size="small" className="up" onClick={() => this.handleEditUser(record)}>
                            <i className="iconfont anticon-bianji" /> 编辑
                        </Button>&nbsp;&nbsp;&nbsp;
                        <Button size="small" className="up" onClick={() => this.handleStop(record)}>
                            <i className="iconfont anticon-jinzhi" /> 禁用
                        </Button>
                    </div> :
                    <div>
                        <Button size="small" className="up" onClick={() => this.handleUp(record)}>
                            <i className="iconfont anticon-qiyong" /> 启用
                        </Button>&nbsp;&nbsp;&nbsp;
                        <Button size="small" className="up" onClick={() => this.handleDel(record)}>
                            <i className="iconfont anticon-shanchu" /> 删除
                        </Button>
                    </div>;
                }
            }
        ];
        // console.log(this.state.dataSource);
        return (
            <div>
                <MainHeader title="用户管理" />

                <MainContent>
                    <h3>用户列表</h3>

                    <Button onClick={this.handleAddUser}>添加用户</Button>
                    <br />
                    <Table
                        dataSource={this.state.dataSource}
                        columns={columns}
                        size={'small'}
                    />
                </MainContent>
            </div>
        );
    }
}

class AddEditUser extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: true
        };
    }

    componentDidMount() {
        const { info, type } = this.props;
        if (type === EnumModalType.edit.type) {
            this.props.form.setFieldsValue({
                user_email: info.user_email,
                user_phone: info.user_phone,
                user_name: info.user_name,
                account_id: info.account_id,
            });
        }
    }

    handleOk = () => {
        // 提取表单内容
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                // user_name, user_phone, user_password, user_email, account_id
                if (this.props.type === EnumModalType.add.type) {
                    addUserAction(values.user_name, values.user_phone, values.user_password, values.user_email, values.account_id).then(resp => {
                        T.prompt.success('保存成功');
                        this.setState({
                            visible: false
                        });
                    }, resp => {
                        T.prompt.error(resp.msg);
                    });
                } else {
                    updateUserAction(this.props.info.user_id, values.user_name, values.user_phone, values.user_email, values.account_id).then(resp => {
                        T.prompt.success('修改成功');
                        this.setState({
                            visible: false
                        });
                    }, resp => {
                        T.prompt.error(resp.msg);
                    });
                }

            }
        });
    };


    ComfirmPassword = (rule, value, callback) => {
        const form = this.props.form;
        if (value && value !== form.getFieldValue('user_password')) {
            callback('密码不一致!');
        } else {
            callback();
        }
    };

    render() {
        const { type } = this.props;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 18 },
            },
        };
        // user_name, user_email, user_password, user_phone, account_id
        const { getFieldDecorator } = this.props.form;
        return (<Modal
            title={EnumModalType[type].label + '用户'}
            visible={this.state.visible}
            onOk={this.handleOk}
            onCancel={() => this.setState({ visible: false })}
            okText={'保存'}
            cancelText={'取消'}
            >
            <Form>
                <FormItem
                    {...formItemLayout}
                    label="用户名"
                    hasFeedback
                    >
                    {getFieldDecorator('user_name', {
                            rules: [{
                            }, {
                                required: true, message: '请输入姓名!',
                            }],
                        })(
                            <Input placeholder="请输入用户名" />
                        )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="邮箱"
                    hasFeedback
                    >
                    {getFieldDecorator('user_email', {
                            rules: [{
                                type: 'email', message: '邮箱格式错误!',
                            }, {
                                required: true, message: '请输入邮箱！',
                            }],
                        })(
                            <Input placeholder="请输入邮箱" />
                        )}
                </FormItem>
                {
                        type !== EnumModalType.edit.type && <FormItem
                            {...formItemLayout}
                            label="账户密码"
                            hasFeedback
                        >
                            {getFieldDecorator('user_password', {
                                rules: [{
                                    whitespace: true,
                                    required: true, message: '请输入密码！',
                                }],
                            })(
                                <Input placeholder="请输入密码" type="password" />
                            )}
                        </FormItem>
                    }

                {
                        type !== EnumModalType.edit.type && <FormItem
                            {...formItemLayout}
                            label="确认密码"
                            hasFeedback
                        >
                            {getFieldDecorator('comfirmPassword', {
                                rules: [{
                                    whitespace: true,
                                    validator: this.ComfirmPassword
                                }],
                            })(
                                <Input type="password" placeholder="请再次输入密码" />
                            )}
                        </FormItem>
                    }


                <FormItem
                    {...formItemLayout}
                    label="公司id"
                    hasFeedback
                    >
                    {getFieldDecorator('account_id', {
                            rules: [{
                                required: true, message: '请输入公司id！',
                            }],
                        })(
                            <Input placeholder="请输入公司id" />
                        )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="手机号"
                    hasFeedback
                    >
                    {getFieldDecorator('user_phone', {
                            rules: [{
                                required: true, message: '请输入手机号！',
                            }],
                        })(
                            <Input placeholder="请输入手机号" />
                        )}
                </FormItem>
            </Form>
        </Modal>);
    }
}
const AddEditUserForm = Form.create()(AddEditUser);
